using Microsoft.AspNetCore.Mvc;
using UniversalAdminSystem.Application.FileStorage.DTOs;
using UniversalAdminSystem.Application.FileStorage.Interfaces;
using UniversalAdminSystem.Api.Attributes;
using UniversalAdminSystem.Domian.FileStorage.ValueObjects;
using UniversalAdminSystem.Application.Common.Results;
using UniversalAdminSystem.Application.Common.Interfaces;

namespace UniversalAdminSystem.Api.Controllers;

[ApiController]
[Route("api/files")]
public class FileController : ControllerBase
{
    private readonly IFileAppService _fileAppService;
    private readonly IFileStorageService _fileStorageService;
    private readonly IUnitOfWork _unitOfWork;

    public FileController(IFileAppService fileAppService, IFileStorageService fileStorageService, IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
        _fileAppService = fileAppService;
        _fileStorageService = fileStorageService;
    }

    [HttpPost("upload")]
    [RequirePermission("file:Create")]
    public async Task<IActionResult> Upload(IFormFile file, Guid? parentId = null)
    {
        if (file == null || file.Length == 0) return BadRequest(Result.Failure("请选择要上传的文件"));
        try
        {
            var res = await _fileAppService.UploadAsync(file);
            return Ok(Result<FileUploadResultDto>.Success(res));
        }
        catch (Exception ex)
        {
            return BadRequest(Result.Failure(ex.Message));
        }
    }

    [HttpGet("test-permission")]
    [RequirePermission("file:Create")]
    public IActionResult TestPermission()
    {
        return Ok(Result.Success("权限检查通过"));
    }

    // [HttpGet("download/{fileId}")]
    // [RequirePermission("file:download")]
    // public async Task<IActionResult> Download(Guid fileId)
    // {
    //     var result = await _fileAppService.DownloadAsync((FileId)fileId);
    //     return result.IsSuccess ? Ok(result) : BadRequest(result);
    // }

    [HttpGet("list")]
    [RequirePermission("file:Read")]
    public async Task<IActionResult> List()
    {
        var result = await _fileAppService.GetList();
        return Ok(result);
    }

    // [HttpPost("folder")]
    // [RequirePermission("file:create")]
    // public async Task<IActionResult> CreateFolder([FromBody] string name, [FromQuery] Guid? parentId)
    // {
    //     var result = await _fileAppService.CreateFolderAsync(name, parentId.HasValue ? (FileId)parentId.Value : null);
    //     return result.IsSuccess ? Ok(result) : BadRequest(result);
    // }

    // [HttpDelete("{fileId}")]
    // [RequirePermission("file:delete")]
    // public async Task<IActionResult> Delete(Guid fileId)
    // {
    //     var result = await _fileAppService.DeleteAsync((FileId)fileId);
    //     return result.IsSuccess ? Ok(result) : BadRequest(result);
    // }

    // [HttpGet("{fileId}")]
    // [RequirePermission("file:read")]
    // public async Task<IActionResult> GetFileById(Guid fileId)
    // {
    //     var result = await _fileAppService.GetFileByIdAsync((FileId)fileId);
    //     return result.IsSuccess ? Ok(result) : BadRequest(result);
    // }

    [HttpGet("{id}")]
    [RequirePermission("file:Read")]
    public async Task<IActionResult> Download(Guid id)
    {
        try
        {

            var entity = await _fileAppService.GetFileById(id);
            var file = await _fileStorageService.DownloadAsync(entity.Name);
            return new FileStreamResult(file, entity.Type);
        }
        catch (System.Exception)
        {
            return BadRequest(Result.Failure(""));
        }
    }

    [HttpDelete("{id}")]
    [RequirePermission("file:Delete")]
    public async Task<IActionResult> RemoveFile(Guid id)
    {
        try
        {
            await _unitOfWork.BeginTransactionAsync();
            var entity = await _fileAppService.GetFileById(id);
            await _fileStorageService.DeleteAsync(entity.Name);
            await _fileAppService.RemoveFile(entity.Id);
            await _unitOfWork.CommitAsync();
            return Ok(Result.Success());
        }
        catch (System.Exception)
        {
            await _unitOfWork.RollbackAsync();
            return BadRequest(Result.Failure("操作错误"));
        }
    }
}